import toast from './toast';
import alert from './alert';
import confirmDialog, { confirm } from './confirm';
import tooltip from './tooltip';
import modal from './modal';
import loading from './loading';
import { printConsoleBanner } from '../utils/console-banner';
import { scrollLock } from '../utils/scroll-lock';

// 声明全局类型
declare global {
  interface Window {
    adnaan: {
      toast: typeof toast;
      alert: typeof alert;
      confirm: typeof confirmDialog;
      tooltip: typeof tooltip;
      modal: typeof modal;
      loading: typeof loading;
    };
  }
}

/**
 * 全局清理函数
 * 清理所有UI实例，避免内存泄漏
 */
export const cleanupAdnaanUI = () => {
  try {
    // 清理tooltip
    tooltip.hide();
  } catch (e) {
    console.error('Error cleaning up tooltip:', e);
  }
  
  try {
    // 清理loading
    loading.hide();
  } catch (e) {
    console.error('Error cleaning up loading:', e);
  }
  
  try {
    // 解锁滚动
    scrollLock.unlock();
  } catch (e) {
    console.error('Error unlocking scroll:', e);
  }
  
  // Modal和Alert会在各自的定时器中自动清理
};

/**
 * 全局UI初始化器
 * 将UI组件挂载到全局对象，实现像第三方UI库的使用体验
 */
export const initAdnaanUI = () => {
  // 打印版权信息横幅
  printConsoleBanner();
  
  // 在页面卸载时自动清理
  if (typeof window !== 'undefined') {
    window.addEventListener('beforeunload', cleanupAdnaanUI);
  }

  // 挂载到window对象
  if (typeof window !== 'undefined') {
    const uiAPI = {
      toast: {
        success: toast.success,
        error: toast.error,
        info: toast.info,
        warning: toast.warning,
        show: toast.show,
      },
      alert: {
        success: alert.success,
        error: alert.error,
        info: alert.info,
        warning: alert.warning,
        show: alert.show,
        close: alert.close,
      },
      confirm: confirmDialog,
      tooltip: {
        show: tooltip.show,
        hide: tooltip.hide,
      },
      modal: {
        show: modal.show,
        confirm: modal.confirm,
        info: modal.info,
        success: modal.success,
        warning: modal.warning,
        error: modal.error,
      },
      loading: {
        show: loading.show,
        hide: loading.hide,
        isLoading: loading.isLoading,
      },
    };

    // 挂载到全局对象
    window.adnaan = uiAPI;
    (globalThis as any).adnaan = uiAPI;
  }
};

/**
 * UI组件库入口
 * 提供多种导入方式
 */
export const UI = {
  toast,
  alert,
  confirm: confirmDialog,
  confirmDialog,
  tooltip,
  modal,
  loading,

  // 初始化和清理方法
  init: initAdnaanUI,
  cleanup: cleanupAdnaanUI,
};

// 默认导出
export default UI;

// 单独导出各组件（保持向后兼容）
export { toast, alert, confirm, confirmDialog, tooltip, modal, loading };
